package cn.saltybe.analysis.controller.api.statistic;

import cn.saltybe.analysis.entity.result.SecondHandHouseAveragePrice;
import cn.saltybe.analysis.service.SecondHandHouseAveragePriceStatisticServiceImpl;
import cn.saltybe.analysis.util.ApiResponse;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api/statistic/second-hand-house-average-price")
public class SecondHandHouseAveragePriceAPI {
    private SecondHandHouseAveragePriceStatisticServiceImpl secondHandHouseAveragePriceStatisticService;

    @Autowired
    public void setSecondHandHouseAveragePriceStatisticService(SecondHandHouseAveragePriceStatisticServiceImpl secondHandHouseAveragePriceStatisticService) {
        this.secondHandHouseAveragePriceStatisticService = secondHandHouseAveragePriceStatisticService;
    }

    @ResponseBody
    @GetMapping(value = "list")
    public String list(
            @RequestParam(value = "city", required = false, defaultValue = "") String city
    ) throws Exception {
        List<SecondHandHouseAveragePrice> list;
        if (city != null && city.length() > 0) list = secondHandHouseAveragePriceStatisticService.query(city);
        else list = secondHandHouseAveragePriceStatisticService.all();
        JsonArray result = new Gson().toJsonTree(list).getAsJsonArray();
        return ApiResponse.buildSuccessResponse(result).toString();
    }
}
